// 移动端用户的路由处理

const {v4: uuidv4} = require('uuid')
const logger = require('../../utils/logger')
const mysqlUtil = require('../../utils/mysqlUtil')
const redisUtil = require('../../utils/redisUtil')
const util = require('../../utils/util')
const config = require('../../config')
const path = require('path')
const { sendMail } = require('../../utils/mail')
const xlsx = require('node-xlsx').default

module.exports = {

    // 发送邮件验证码
    sendMailCode: async ctx => {
        let args = ctx.request.body
        if (!args.uid) return ctx.body = {code: -1, message: '参数缺失'}
        try {
            logger.debug('send mail code', args.uid)
            let res = await mysqlUtil.execute('SELECT email FROM tb_user WHERE uid = ? LIMIT 1', [args.uid])
            if (res.length == 0) return ctx.body = {code: -1, message: '用户不存在'}
            logger.debug(res[0])
            let mail = res[0].email
            if (!mail) return ctx.body = {code: -1, message: '邮箱未配置'}
            let code = 100001 + Math.floor(899998 * Math.random())
            redisUtil.set('OA:RESET:PWD:TOKEN:' + args.uid, code + '', 'EX', 60)

            await sendMail(mail, '修改密码', '您的验证码为:' + code)
            ctx.body = {code: 0, message: '发送成功'}
        } catch (err) {
            logger.error(err)
            ctx.body = {code: -1, message: 'system error'}
        }
    },

    // 发送短信验证码
    sendSmsCode: async ctx => {
        let args = ctx.request.body
        if (!args.uid) return ctx.body = {code: -1, message: '参数缺失'}
        try {
            logger.debug('send sms code', args.uid)
            let code = 100001 + Math.floor(899998 * Math.random())
            redisUtil.set('OA:RESET:PWD:TOKEN:' + args.uid, code + '', 'EX', 300)
            util.sendVerifyCodeToUser(args.uid, code)
            ctx.body = {code: 0, message: '发送成功'}
        } catch (err) {
            logger.error(err)
            ctx.body = {code: -1, message: 'system error'}
        }
    },

    // 注册
    register: async ctx => {
        ctx.body = {code: 0, message: 'success'}
    },

    // 登录
    login: async ctx => {
        let params = ctx.request.body
        if (!params.phone || !params.password || !params.platform) return ctx.body = {code: -1, message: '参数缺失'}
        let uid = parseInt(params.phone)
        if (!uid) return ctx.body = {code: -1, message: '参数错误'}
        logger.debug('logn uid', uid)
        try {
            let res = await mysqlUtil.execute('SELECT uid, sta FROM tb_user WHERE phone = ? AND password = ? LIMIT 1', [uid, params.password])
            if (res.length == 0) return ctx.body = {code: -1, message: '用户名或密码错误'}
            if (res[0].sta == '离职') return ctx.body = {code: -1, message: '无法登录'}
            let token = uuidv4().replace(/-/g, '')
            redisUtil.set('OA:TOKEN:USER:' + token, res[0].uid, 'EX', 3 * 24 * 60 * 60);
            // redisUtil.set('OA:USER:TOKEN:' + res[0].uid, token, 'EX', 3 * 24 * 60 * 60);
            if (params.platform == 'web'){
                redisUtil.set('OA:USER:WEB:TOKEN:' + res[0].uid, token, 'EX', 3 * 24 * 60 * 60);
            } else if (params.platform == 'app'){
                redisUtil.set('OA:USER:APP:TOKEN:' + res[0].uid, token, 'EX', 3 * 24 * 60 * 60);
            }
            ctx.body = {code: 0, message: 'success', data: token}
        } catch (err) {
            logger.error(err)
            ctx.body = {code: -1, message: 'system error'}
        }
    },

    // 获取最新版本
    getLatestVersion: async ctx => {
        try {
            let res = await mysqlUtil.execute('SELECT * FROM con_version WHERE sta = 1 ORDER BY id DESC LIMIT 1')
            if (res.leng == 0) return ctx.body = {code: 0, message:'', data: {ver: '999.999.999', url: ''}}
            ctx.body = {code: 0, message: '', data: res[0]}
        } catch (err) {
            logger.error(err)
            ctx.body = {code: -1, message: 'system error'}
        }
    },

    modifyAvatar: async ctx => {
        let files = ctx.request.files
        logger.debug(files)
        if (!files || !files.file || !files.file.filepath) return ctx.body = {code: -1, message: '头像上传失败'}
        
        let params = ctx.request.body
        logger.debug('modify avatar params', params)
        if (!params || !params.token) return ctx.body = {code: -1, message: '参数缺失'}
        let uid = parseInt(params.uid)
        if (!uid) return ctx.body = {code: -1, message: '参数错误'}
        // let curToken = await redisUtil.get('OA:USER:TOKEN:' + uid);
        // if (params.token != curToken) return ctx.body = {code: 9999, message: '请重新登录'};
        
        let basename = path.basename(files.file.filepath)
        logger.debug('modify avatar base', basename)
        try {
            let sql = 'UPDATE tb_user SET avatar = ? WHERE uid = ? LIMIT 1'
            let res = await mysqlUtil.execute(sql, [config.baseUrl + basename, uid])
            if (res.affectedRows == 0) return ctx.body = {code: -1, message: '用户不存在'}
            ctx.body = {code: 0, message: 'success'}
        } catch (err) {
            logger.error(err)
            ctx.body = {code: -1, message: 'system error'}
        }

        ctx.body = {code: 0, message: 'success'}
    },

    modifySign: async ctx => {
        let files = ctx.request.files
        logger.debug(files)
        if (!files || !files.file || !files.file.filepath) return ctx.body = {code: -1, message: '签名上传失败'}
        
        let params = ctx.request.body
        logger.debug('modify avatar params', params)
        if (!params || !params.token) return ctx.body = {code: -1, message: '参数缺失'}
        let uid = parseInt(params.uid)
        if (!uid) return ctx.body = {code: -1, message: '参数错误'}
        // let curToken = await redisUtil.get('OA:USER:TOKEN:' + uid);
        // if (params.token != curToken) return ctx.body = {code: 9999, message: '请重新登录'};
        
        let basename = path.basename(files.file.filepath)
        logger.debug('modify sign base', basename)
        try {
            let sql = 'UPDATE tb_user SET signimg = ? WHERE uid = ? LIMIT 1'
            let res = await mysqlUtil.execute(sql, [config.baseUrl + basename, uid])
            if (res.affectedRows == 0) return ctx.body = {code: -1, message: '用户不存在'}
            ctx.body = {code: 0, message: 'success'}
        } catch (err) {
            logger.error(err)
            ctx.body = {code: -1, message: 'system error'}
        }
    },

    modifySignGet: async ctx => {
        let args = ctx.query
        if (!args || !args.uid || !args.url) return ctx.body = {code: -1, message: '参数缺失'}

        let uid = parseInt(args.uid)
        try {
            let sql = 'UPDATE tb_user SET signimg = ? WHERE uid = ? LIMIT 1';
            await mysqlUtil.execute(sql, [args.url, uid])
            ctx.body = {code: 0, message: 'success'}
        } catch (err) {
            logger.error(err)
            ctx.body = {code: -1, message: 'system error'}
        }
    },

    uploadFile: async ctx => {

        let files = ctx.request.files
        logger.debug("uploadFile", files)
        if (!files || !files.file || !files.file.filepath) return ctx.body = {code: -1, message: '文件上传失败'}
        
        // let params = ctx.request.body
        // if (!params || !params.token) return ctx.body = {code: -1, message: '参数缺失'}
        // let uid = parseInt(params.uid)
        // if (!uid) return ctx.body = {code: -1, message: '参数错误'}
        // let curToken = await redisUtil.get('OA:USER:TOKEN:' + uid);
        // if (params.token != curToken) return ctx.body = {code: 9999, message: '请重新登录'};

        let basename = path.basename(files.file.filepath)

        logger.debug("uploadFile", files.file.filepath)

        ctx.body = {code: 0, message: 'success', data: config.baseUrl + basename}
    },

    uploadGongzi: async ctx => {

        let files = ctx.request.files
        if (!files || !files.file || !files.file.filepath) return ctx.body = {code: -1, message: '文件上传失败'}

        let params = ctx.request.body
        let id = parseInt(params.id)
        if (!id) return ctx.body = {code: -1, message: '参数缺失'}

        let totalCnt = 0
        let totalAmount = 0

        try {

            // 删除之前上传的
            await mysqlUtil.execute('DELETE FROM tb_user_gongzi WHERE uploadId = ?', [id])

            const sheets = xlsx.parse(files.file.filepath)
            if (sheets.length == 0) return ctx.body = {code: -1, message: '数据解析错误'}
            let data = sheets[0].data
            for (let i = 1; i < data.length; i++) {
                // 月份
                let yuefen = data[i][1]
                if (typeof yuefen == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行月份未填写'}

                // 工号
                let uid = parseInt(data[i][2])
                if (!uid) return ctx.body = {code: -1, message: '第' + i + '行工号填写错误'}

                // 姓名
                let name = data[i][3]
                if (typeof name == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行姓名未填写'}

                // 岗位工资
                let gangweigongzi = data[i][4]
                if (typeof gangweigongzi == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行岗位工资未填写'}
                gangweigongzi = parseFloat(gangweigongzi)
                if (isNaN(gangweigongzi)) return ctx.body = {code: -1, message: '第' + i + '行岗位工资格式填写错误'}

                // 薪级工资
                let xinjigongzi = data[i][5]
                if (typeof xinjigongzi == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行薪级工资未填写'}
                xinjigongzi = parseFloat(xinjigongzi)
                if (isNaN(xinjigongzi)) return ctx.body = {code: -1, message: '第' + i + '行薪级工资格式填写错误'}

                // 岗位津贴
                let gangweijintie = data[i][6]
                if (typeof gangweijintie == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行岗位津贴未填写'}
                gangweijintie = parseFloat(gangweijintie)
                if (isNaN(gangweijintie)) return ctx.body = {code: -1, message: '第' + i + '行岗位津贴格式填写错误'}

                // 生活补贴
                let shenghuobutie = data[i][7]
                if (typeof shenghuobutie == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行生活补贴未填写'}
                shenghuobutie = parseFloat(shenghuobutie)
                if (isNaN(shenghuobutie)) return ctx.body = {code: -1, message: '第' + i + '行生活补贴格式填写错误'}

                // 基础增核
                let jichuzenghe = data[i][8]
                if (typeof jichuzenghe == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行基础增核未填写'}
                jichuzenghe = parseFloat(jichuzenghe)
                if (isNaN(jichuzenghe)) return ctx.body = {code: -1, message: '第' + i + '行基础增核格式填写错误'}

                // 交通补贴
                let jiaotongbutie = data[i][9]
                if (typeof jiaotongbutie == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行交通补贴未填写'}
                jiaotongbutie = parseFloat(jiaotongbutie)
                if (isNaN(jiaotongbutie)) return ctx.body = {code: -1, message: '第' + i + '行交通补贴格式填写错误'}

                // 医补
                let yibu = data[i][10]
                if (typeof yibu == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行医补未填写'}
                yibu = parseFloat(yibu)
                if (isNaN(yibu)) return ctx.body = {code: -1, message: '第' + i + '行医补格式填写错误'}

                // 特岗津贴
                let tegangjintie = data[i][11]
                if (typeof tegangjintie == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行特岗津贴未填写'}
                tegangjintie = parseFloat(tegangjintie)
                if (isNaN(tegangjintie)) return ctx.body = {code: -1, message: '第' + i + '行特岗津贴格式填写错误'}

                // 公务交通补贴
                let gongwujiaotongbutie = data[i][12]
                if (typeof gongwujiaotongbutie == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行公务交通未填写'}
                gongwujiaotongbutie = parseFloat(gongwujiaotongbutie)
                if (isNaN(gongwujiaotongbutie)) return ctx.body = {code: -1, message: '第' + i + '行公务交通格式填写错误'}

                // 奖励性绩效
                let jianglixingjixiao = data[i][13]
                if (typeof jianglixingjixiao == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行奖励性绩效未填写'}
                jianglixingjixiao = parseFloat(jianglixingjixiao)
                if (isNaN(jianglixingjixiao)) return ctx.body = {code: -1, message: '第' + i + '行奖励性绩效格式填写错误'}

                // 住房补贴
                let zhufangbutie = data[i][14]
                if (typeof zhufangbutie == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行住房补贴未填写'}
                zhufangbutie = parseFloat(zhufangbutie)
                if (isNaN(zhufangbutie)) return ctx.body = {code: -1, message: '第' + i + '行住房补贴格式填写错误'}

                // 年底奖励性绩效
                let niandijianglixingjixiao = data[i][15]
                if (typeof niandijianglixingjixiao == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行年底奖励性绩效未填写'}
                niandijianglixingjixiao = parseFloat(niandijianglixingjixiao)
                if (isNaN(niandijianglixingjixiao)) return ctx.body = {code: -1, message: '第' + i + '行年底奖励性绩效格式填写错误'}

                // 增量绩效
                let zengliangjixiao = data[i][16]
                if (typeof zengliangjixiao == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行增量绩效未填写'}
                zengliangjixiao = parseFloat(zengliangjixiao)
                if (isNaN(zengliangjixiao)) return ctx.body = {code: -1, message: '第' + i + '行增量绩效格式填写错误'}

                // 应发工资
                let yingfagongzi = data[i][17]
                if (typeof yingfagongzi == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行应发工资未填写'}
                yingfagongzi = parseFloat(yingfagongzi)
                if (isNaN(yingfagongzi)) return ctx.body = {code: -1, message: '第' + i + '行应发工资格式填写错误'}

                // 养老保险
                let yanglaobaoxian = data[i][18]
                if (typeof yanglaobaoxian == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行养老保险未填写'}
                yanglaobaoxian = parseFloat(yanglaobaoxian)
                if (isNaN(yanglaobaoxian)) return ctx.body = {code: -1, message: '第' + i + '行养老保险格式填写错误'}

                // 职业年金
                let zhiyenianjin = data[i][19]
                if (typeof zhiyenianjin == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行职业年金未填写'}
                zhiyenianjin = parseFloat(zhiyenianjin)
                if (isNaN(zhiyenianjin)) return ctx.body = {code: -1, message: '第' + i + '行职业年金格式填写错误'}

                // 医保
                let yibao = data[i][20]
                if (typeof yibao == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行医保未填写'}
                yibao = parseFloat(yibao)
                if (isNaN(yibao)) return ctx.body = {code: -1, message: '第' + i + '行医保格式填写错误'}

                // 公积金
                let gongjijin = data[i][21]
                if (typeof gongjijin == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行公积金未填写'}
                gongjijin = parseFloat(gongjijin)
                if (isNaN(gongjijin)) return ctx.body = {code: -1, message: '第' + i + '行公积金格式填写错误'}

                // 工会会费
                let gonghuihuifei = data[i][22]
                if (typeof gonghuihuifei == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行工会会费未填写'}
                gonghuihuifei = parseFloat(gonghuihuifei)
                if (isNaN(gonghuihuifei)) return ctx.body = {code: -1, message: '第' + i + '行工会会费格式填写错误'}

                // 预扣个税
                let yukougeshui = data[i][23]
                if (typeof yukougeshui == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行预扣个税未填写'}
                yukougeshui = parseFloat(yukougeshui)
                if (isNaN(yukougeshui)) return ctx.body = {code: -1, message: '第' + i + '行预扣个税格式填写错误'}

                // 补扣养老保险
                let bukouyanglaobaoxian = data[i][24]
                if (typeof bukouyanglaobaoxian == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行补扣养老保险未填写'}
                bukouyanglaobaoxian = parseFloat(bukouyanglaobaoxian)
                if (isNaN(bukouyanglaobaoxian)) return ctx.body = {code: -1, message: '第' + i + '行补扣养老保险格式填写错误'}

                // 补扣职业年金
                let bukouzhiyenianjin = data[i][25]
                if (typeof bukouzhiyenianjin == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行补扣职业年金未填写'}
                bukouzhiyenianjin = parseFloat(bukouzhiyenianjin)
                if (isNaN(bukouzhiyenianjin)) return ctx.body = {code: -1, message: '第' + i + '行补扣职业年金格式填写错误'}

                // 补扣公积金
                let bukougongjijin = data[i][26]
                if (typeof bukougongjijin == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行补扣公积金未填写'}
                bukougongjijin = parseFloat(bukougongjijin)
                if (isNaN(bukougongjijin)) return ctx.body = {code: -1, message: '第' + i + '行补扣公积金格式填写错误'}

                // 补发岗位工资
                let bufagangweigongzi = data[i][27]
                if (typeof bufagangweigongzi == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行补发岗位工资未填写'}
                bufagangweigongzi = parseFloat(bufagangweigongzi)
                if (isNaN(bufagangweigongzi)) return ctx.body = {code: -1, message: '第' + i + '行补发岗位工资格式填写错误'}

                // 补发薪级
                let bufaxinji = data[i][28]
                if (typeof bufaxinji == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行补发薪级未填写'}
                bufaxinji = parseFloat(bufaxinji)
                if (isNaN(bufaxinji)) return ctx.body = {code: -1, message: '第' + i + '行补发薪级格式填写错误'}

                // 补发岗位津贴
                let bufagangweijintie = data[i][29]
                if (typeof bufagangweijintie == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行补发岗位津贴未填写'}
                bufagangweijintie = parseFloat(bufagangweijintie)
                if (isNaN(bufagangweijintie)) return ctx.body = {code: -1, message: '第' + i + '行补发岗位津贴格式填写错误'}

                // 补发基础增核
                let bufajichuzenghe = data[i][30]
                if (typeof bufajichuzenghe == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行补发基础增核未填写'}
                bufajichuzenghe = parseFloat(bufajichuzenghe)
                if (isNaN(bufajichuzenghe)) return ctx.body = {code: -1, message: '第' + i + '行补发基础增核格式填写错误'}

                // 补发特岗津贴
                let bufategangjintie = data[i][31]
                if (typeof bufategangjintie == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行补发特岗津贴未填写'}
                bufategangjintie = parseFloat(bufategangjintie)
                if (isNaN(bufategangjintie)) return ctx.body = {code: -1, message: '第' + i + '行补发特岗津贴格式填写错误'}

                // 补发住房补贴
                let bufazhufangbutie = data[i][32]
                if (typeof bufazhufangbutie == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行补发住房补贴未填写'}
                bufazhufangbutie = parseFloat(bufazhufangbutie)
                if (isNaN(bufazhufangbutie)) return ctx.body = {code: -1, message: '第' + i + '行补发住房补贴格式填写错误'}

                // 实发工资
                let shifagongzi = data[i][33]
                if (typeof shifagongzi == 'undefined') return ctx.body = {code: -1, message: '第' + i + '行实发工资未填写'}
                shifagongzi = parseFloat(shifagongzi)
                if (isNaN(shifagongzi)) return ctx.body = {code: -1, message: '第' + i + '行实发工资格式填写错误'}

                // 备注
                let remark = data[i][34] || ''

                let gongziInfo = {
                    uid,
                    name,
                    yuefen,
                    gangweigongzi,
                    xinjigongzi,
                    gangweijintie,
                    shenghuobutie,
                    jichuzenghe,
                    jiaotongbutie,
                    yibu,
                    tegangjintie,
                    gongwujiaotongbutie,
                    jianglixingjixiao,
                    zhufangbutie,
                    niandijianglixingjixiao,
                    zengliangjixiao,
                    yingfagongzi,
                    yanglaobaoxian,
                    zhiyenianjin,
                    yibao,
                    gongjijin,
                    gonghuihuifei,
                    yukougeshui,
                    bukouyanglaobaoxian,
                    bukouzhiyenianjin,
                    bukougongjijin,
                    bufagangweigongzi,
                    bufaxinji,
                    bufagangweijintie,
                    bufajichuzenghe,
                    bufategangjintie,
                    bufazhufangbutie,
                    shifagongzi,
                    remark,
                    uploadId: id,
                    createTime: Date.now(),
                    updateTime: Date.now()
                }

                await mysqlUtil.execute('INSERT INTO tb_user_gongzi SET ?', [ gongziInfo ])

                totalCnt++
                totalAmount += shifagongzi

                logger.debug(totalCnt, totalAmount)
            }
            await mysqlUtil.execute('UPDATE tb_gongzi_upload SET totalCnt = ?, totalAmount = ? WHERE id = ? LIMIT 1', [totalCnt, totalAmount, id])
            ctx.body = {code: 0, message: 'success'}
        } catch (err) {
            logger.error(err)
            ctx.body = {code: -1, message: '文件解析错误'}
        }
    },

    // 重置密码
    resetPwd: async ctx => {
        let args = ctx.request.body
        if (!args.uid || !args.code || !args.pwd) return ctx.body = {code: -1, message: '参数缺失'}
        try {
            let code = await redisUtil.get('OA:RESET:PWD:TOKEN:' + args.uid)
            if (code != args.code) return ctx.body = {code: -1, message: '验证码已过期'}
            await mysqlUtil.execute('UPDATE tb_user SET password = ? WHERE uid = ? LIMIT 1', [args.pwd, args.uid])
            ctx.body = {code: 0, message: 'success'}
        } catch (err) {
            logger.error(err)
        }
    }
}